import QtQuick 1.0



 Flickable {
     //animation lors des deplacements
     Behavior on contentX {
	 SpringAnimation {spring: 2; damping: 0.2 } 
     }
     Behavior on contentY {
         SpringAnimation { spring: 2; damping: 0.2 } 
     }
     
     //clip:true ??
     id:myFlickable
     
     focus:true
     property Item currentSelected
     
     function selectItem(it) {
	it.focus=true;
	currentSelected=it;
	centerOn(it);
     }
     function selectIndex(i) {
	selectItem(myFlickable.contentItem.children[i]);
     }
     
     function centerOn(it) {
        var cX = it.x;
	var cY = it.y;
	cX += (it.width - width)/2;
	cY += ( it.height - height)/2;
	contentX = cX;
	contentY = cY;
     }
     
     /*
      * 1 ==> left,
      * 2 ==> down
      * 3 ==> right
      * 4 ==> up
     */
     function navigue(dir){
       console.log('childreen :' + myFlickable.contentItem.children.length);
       
       if(!currentSelected){
	 console.log('pas d element focusé, on prend le premier');
	 if(myFlickable.contentItem.children.length>0)
	   selectIndex(0);
	 
	 return;
       }
       
       var dmin = false;
       var itCandidat = false;
       
       
       for(var i=0;i<myFlickable.contentItem.children.length;i++){
	 var it = myFlickable.contentItem.children[i];
	 if(it==currentSelected)
	   continue;
	 
	 var dx = (dir==1||dir==3)? it.x - currentSelected.x: it.y - currentSelected.y;
	 
	 //console.log('dx:' + dx);
	  
	 if( (dir==1|| dir==4) && dx>=0)
	   continue; //deplacement left/up, on cherche des negatifs stricts
	   
	 if( (dir==3 || dir==2) && dx<=0)
	   continue; //deplacement right/down, on cherche des positifs stricts
	   
	 dx = Math.abs(dx);
	 //console.log('distance: '+ dx);
	 
	 if(!dmin || dmin > dx){
	   dmin = dx;
	   itCandidat = it;
	 }
	 //console.log('dmin: '+ dmin);
       }
       
       if(itCandidat){
	 //console.log('itCandidat: '+ itCandidat);
	 selectItem(itCandidat);
       }
     }
     
    Keys.onDownPressed : {
	navigue(2);
    }
    Keys.onUpPressed : {
	navigue(4);
    }
    Keys.onLeftPressed : {
	navigue(1);
    }
    Keys.onRightPressed : {
	navigue(3);
    }
    
 }
 